package com.lbs.jiepiaisi.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.base.ErrorException;
import com.lbs.jiepiaisi.base.ProgressObserver;
import com.lbs.jiepiaisi.bean.EqnoLoginBean;
import com.lbs.jiepiaisi.bean.PhotoImgBean;
import com.lbs.jiepiaisi.bean.TracingBean;
import com.lbs.jiepiaisi.bean.UploadImageBean;
import com.lbs.jiepiaisi.config.Api;
import com.lbs.jiepiaisi.config.ProgressRequestBody;
import com.lbs.jiepiaisi.fragment.PhotoFragment.UploadImgType;
import com.lbs.jiepiaisi.manager.CommonScanActivityManager;
import com.lbs.jiepiaisi.utils.BitmapUtils;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.DialogUtil;
import com.lbs.jiepiaisi.utils.PhoneUtil;
import com.lbs.jiepiaisi.utils.RxSchedulers;
import com.lbs.jiepiaisi.utils.ToastUtil;
import com.lbs.jiepiaisi.utils.Utils;
import com.lbs.jiepiaisi.utils.ValidUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


/**
 * 时间：2017/6/22 09:40
 * 作用：
 */
public class PhotoActivity extends BaseActivity implements AMapLocationListener, GeocodeSearch.OnGeocodeSearchListener {

    private static final int REQUEST_PERMISSION = 0x002;

    private LinearLayout ll_pic_1;
    private ImageView photoBtn1;
    private ImageView imageView1;

    private LinearLayout ll_pic_2;
    private ImageView photoBtn2;
    private ImageView imageView2;

    private LinearLayout ll_pic_3;
    private ImageView photoBtn3;
    private ImageView imageView3;

    private List<LocalMedia> picsList = new ArrayList<LocalMedia>() {{
        add(new LocalMedia());add(new LocalMedia());add(new LocalMedia());
    }};

    private List<String> typeList = new ArrayList<String>() {{
        add("1");add("2");add("3");
    }};

    //@Bind(R.id.btn_upload)
    private Button uploadBtn;
    private PhotoImgBean photoImgBean;
    private EqnoLoginBean eqnoLoginBean;
    private String installPosition;
    private String eqPosition;

    //@Bind(R.id.tv_eqDeptName)
    private TextView eqDeptName;
    //@Bind(R.id.tv_ownerName)
    private TextView ownerName;
    private TextView eqNo;
    private TextView sim;
    private TextView statusTV;
    private TextView eqPositionTV;
    private EditText installerET;
    private EditText installerPhoneET;

    private TextView timeTV;//定位时间

    public AMapLocationClient mlocationClient;//声明mlocationClient对象
    public AMapLocationClientOption mLocationOption;//声明mLocationOption对象

    private LinearLayout[] allLinearLayouts = new LinearLayout[3];//所有拍照布局

    private UploadImgType uploadImgType;

    private GeocodeSearch installerGeocodeSearch;//逆地理编码转换对象
    private RegeocodeQuery installerRegeocodeQuery;

    private GeocodeSearch eqGeocodeSearch;//逆地理编码转换对象
    private RegeocodeQuery eqRegeocodeQuery;

    private TracingBean.Result tracingResult;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
//        ButterKnife.bind(this);
        //CommonScanActivityManager.addActivity(this);

        //请求权限
        PackageManager pkgManager = getPackageManager();

        boolean cameraPermission =
                pkgManager.checkPermission(Manifest.permission.CAMERA, getPackageName()) == PackageManager.PERMISSION_GRANTED;
        boolean writeExternalStoragePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !cameraPermission || !writeExternalStoragePermission) {
            requestPermission();
        }
        getExtras();
        findView();
        setListener();
        initLocation();
        initGeocodeSearch();
        initAddPhotoView();

    }

    private void getExtras() {
        Bundle bundle = getIntent().getExtras();
        eqnoLoginBean = (EqnoLoginBean) bundle.getSerializable("eqnoLoginBean");
        photoImgBean = (PhotoImgBean) bundle.getSerializable("photoImgBean");
        uploadImgType = (UploadImgType) bundle.getSerializable("uploadImgType");
    }

    public void initAddPhotoView() {
        if (uploadImgType == UploadImgType.UploadImgTypeNormal) {
            return;
        }

        List<PhotoImgBean.FileInfo> files = photoImgBean.getFiles();
        for (PhotoImgBean.FileInfo fileInfo : files) {
            allLinearLayouts[fileInfo.getType() - 1].setVisibility(View.GONE);
        }

        Iterator<String> it = typeList.iterator();
        while(it.hasNext()){
            String x = it.next();
            for (PhotoImgBean.FileInfo fileInfo : files) {
                if ((fileInfo.getType()+"").equals(x)) {
                    it.remove();
                }
            }
        }

        titleView.setText("补拍");
        uploadBtn.setText("补拍提交");
        installerET.setEnabled(false);
        installerET.setBackgroundColor(getResources().getColor(R.color.backgroundgray));
        installerET.setText(photoImgBean.getInstallInfo().getInstaller());
        installerPhoneET.setEnabled(false);
        installerPhoneET.setBackgroundColor(getResources().getColor(R.color.backgroundgray));
        installerPhoneET.setText(photoImgBean.getInstallInfo().getInstallerPhone());
        installerET.clearFocus();
        installerPhoneET.clearFocus();
        closeKeyboard();
    }

    private void closeKeyboard() {
        findViewById(R.id.text_notuse).requestFocus();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            mlocationClient.stopLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void findView() {
        /** ********************图片一***************************/
        ll_pic_1 = (LinearLayout) findViewById(R.id.ll_1);
        photoBtn1 = (ImageView) findViewById(R.id.btn_photo_1);
        imageView1 = findViewById(R.id.image_view_1);
        allLinearLayouts[0] = ll_pic_1;
        /** ********************图片二***************************/
        ll_pic_2 = (LinearLayout) findViewById(R.id.ll_2);
        photoBtn2 = (ImageView) findViewById(R.id.btn_photo_2);
        imageView2 = (ImageView) findViewById(R.id.image_view_2);
        allLinearLayouts[1] = ll_pic_2;
        /** ********************图片三***************************/
        ll_pic_3 = (LinearLayout) findViewById(R.id.ll_3);
        photoBtn3 = (ImageView) findViewById(R.id.btn_photo_3);
        imageView3 = (ImageView) findViewById(R.id.image_view_3);
        allLinearLayouts[2] = ll_pic_3;

        /** *********************上传**********************/
        uploadBtn = findViewById(R.id.btn_upload);

        /** 经销商名称*/
        eqDeptName = (TextView) findViewById(R.id.tv_eqDeptName);
        if (eqnoLoginBean.getResult() != null && !("null" .equals(eqnoLoginBean.getResult().getEqDeptName()))) {
            eqDeptName.setText(eqnoLoginBean.getResult().getEqDeptName());
        } else {
            eqDeptName.setText("暂无经销商");
        }

        /** 车主姓名*/
        ownerName = (TextView) findViewById(R.id.tv_ownerName);
        if (eqnoLoginBean.getResult() != null && !("null" .equals(eqnoLoginBean.getResult().getOwnerName()))) {
            ownerName.setText(eqnoLoginBean.getResult().getOwnerName());
        } else {
            ownerName.setText("暂无车主");
        }

        /** 设备号*/
        eqNo = (TextView) findViewById(R.id.tv_eqNo);
        if (eqnoLoginBean.getResult() != null && !("null" .equals(eqnoLoginBean.getResult().getEqNo()))) {
            eqNo.setText(eqnoLoginBean.getResult().getEqNo());
        } else {
            eqNo.setText("暂无设备号");
        }
        /** SIM号*/
        sim = findViewById(R.id.tv_sim);
        if (eqnoLoginBean.getResult() != null && !("null" .equals(eqnoLoginBean.getResult().getSim()))) {
            sim.setText(eqnoLoginBean.getResult().getSim());
        } else {
            sim.setText("暂无SIM卡号");
        }

        /** 设备状态*/
        statusTV = findViewById(R.id.tv_status);
        statusTV.setText("设备状态：" + getStatus());
        /** 定位位置*/
        eqPositionTV = findViewById(R.id.tv_location);
        if (eqnoLoginBean.getResult() == null || eqnoLoginBean.getResult().getPoint() == null || eqnoLoginBean.getResult().getPoint().getPositionTime() == null) {
            eqPositionTV.setText("定位位置：无位置信息");
        }

        /** 定位时间*/
        timeTV = findViewById(R.id.tv_time);
        if (eqnoLoginBean.getResult() == null || eqnoLoginBean.getResult().getPoint() == null || eqnoLoginBean.getResult().getPoint().getPositionTime() == null) {
            timeTV.setText("定位时间：无位置信息");
        } else {
            timeTV.setText("定位时间：" + eqnoLoginBean.getResult().getPoint().getPositionTime());
        }

        installerET = findViewById(R.id.et_installer);
        installerPhoneET = findViewById(R.id.et_install_phone);

    }

    private void setListener() {

        // 图片一
        photoBtn1.setOnClickListener(v -> {
            if (ButtonUtil.isFastClick()) {
                PictureSelector.create(PhotoActivity.this)
                        .openCamera(PictureMimeType.ofImage())
                        .forResult(1);
            }
        });
        // 图片二
        photoBtn2.setOnClickListener(v -> PictureSelector.create(PhotoActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .forResult(2));
        // 图片三
        photoBtn3.setOnClickListener(v -> PictureSelector.create(PhotoActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .forResult(3));

        /** 图片点击放大*/
        imageView1.setOnClickListener(v -> {
            if (picsList.get(0) != null) {
                PictureSelector.create(PhotoActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(0, picsList);
            }
        });

        imageView2.setOnClickListener(v -> {
            if (picsList.get(1) != null) {
                PictureSelector.create(PhotoActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(1, picsList);
            }
        });

        imageView3.setOnClickListener(v -> {
            if (picsList.get(2) != null) {
                PictureSelector.create(PhotoActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(2, picsList);
            }
        });

        uploadBtn.setOnClickListener(v -> uploadFiles());
    }

    //补拍上传图片
    private void uploadSupplementPhoto() {
        if (eqnoLoginBean.getResult() != null && "3".equals(eqnoLoginBean.getResult().getStatus())) {
            ToastUtil.show("该设备未启用");
            return;
        }

        if (tracingResult == null || tracingResult.getPostType() == null || tracingResult.getPositionTime() == null || tracingResult.getGdLat() == 0) {
            ToastUtil.show("该设备未定位");
            return;
        }

        if (tracingResult.getPostType().equals("LBS")) {
            ToastUtil.show("GPS信号弱，请重新定位");
            return;
        }

        /** 比较定位时间*/
        int disTime = Utils.compareTime(tracingResult.getPositionTime(), Utils.getNowTime());
        Log.e("hyhyhyhyhyhy",disTime+"");
        //Log.e("hyhyhyhyhyhy","timeTV = "+timeTV.getText().toString()+"--"+"nowTime = "+Utils.getNowTime());
        if (disTime > 30) {
            ToastUtil.show("定位失效，请重新定位");
            return;
        }

        double distance = Utils.calculateLineDistance(mCurAMapLocation.getLatitude(), mCurAMapLocation.getLongitude(), tracingResult.getGdLat(), tracingResult.getGdLng());
        if (distance > 500.0) {
            ToastUtil.show("请在安装现场拍照");
            return;
        }

        int index = 0;
        for (LocalMedia media : picsList) {
            if (media.getPath() != null) {
                index++;
            }
        }

        if (index != typeList.size()) {
            ToastUtil.show("补拍照片不完整");
            return;
        }

        DialogUtil.show(mContext, "正在处理...");
        new Thread(){
            @Override
            public void run() {
                int index = 0;
                for (LocalMedia media : picsList) {
                    if (media.getPath() != null) {
                        int finalIndex = index;
                        mContext.runOnUiThread(() -> DialogUtil.setContent("正在压缩第" + (finalIndex + 1) + "张图片"));
                        compressImage(media.getPath(), index);
                        MultipartBody multipartBody = fetchSupplementMutipartBody(index);
                        multipartBodyList.add(multipartBody);
                        try {
                            sTotalContentLength += multipartBody.contentLength();//计算总文件大小
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Log.e("88888777", "压缩第" + (index + 1) + "张");
                        index++;
                    }
                }
                // 统一压缩完后，这里单张上传
                uploadSupplementFiles();
            }
        }.start();
    }

    private List<MultipartBody> multipartBodyList = new ArrayList<>();
    private long sTotalContentLength = 0;
    private long sWrittenTotalContentLength = 0;
    private int sIndex = 0;
    private long sWrittenCurrentContentLen = 0;

    private void uploadSupplementFiles() {/** 上传补拍照片*/

        MultipartBody multipartBody = multipartBodyList.get(sIndex);

        ProgressRequestBody requestBody = new ProgressRequestBody(multipartBody, (totalLen, writtenLen) -> {
            sWrittenTotalContentLength = sWrittenCurrentContentLen + writtenLen;
            if (writtenLen == totalLen) {
                sWrittenCurrentContentLen = sWrittenTotalContentLength;
            }
            Log.e("&&&&&&&11111",sWrittenTotalContentLength + "--" + sWrittenTotalContentLength + "--" + sTotalContentLength);
            Log.e("&&&&&&&111112222222","进度 = " + 100 * sWrittenTotalContentLength / sTotalContentLength + "%");
            mContext.runOnUiThread(() -> DialogUtil.setContent("正在上传图片：" + 100 * sWrittenTotalContentLength / sTotalContentLength + "%"));
        });

        Api.getInstance().createService()
                .repeatUploadFiles(requestBody)
                .compose(RxSchedulers.observableIO2Main(mContext))
                .subscribe(new ProgressObserver<UploadImageBean>(mContext, false) {

                    @Override
                    public void onSuccess(UploadImageBean result) {
                        if (sIndex + 1 == typeList.size()) { // 所有补拍照片都上传成功才退出当前界面
                            new Handler().postDelayed(() -> {
                                DialogUtil.dismiss();
                                ToastUtil.show("上传成功");
                                PhotoActivity.this.finish();
                            }, 1 * 1000);
                            return;
                        }

                        sIndex++;
                        uploadSupplementFiles();
                    }

                    @Override
                    public void onFailure(ErrorException e) {
                        DialogUtil.dismiss();
                        ToastUtil.show("上传失败["+e.getMsg()+"]");
                        Log.e("666666","补拍照片上传失败"+e.getMsg());
                    }
                });
    }

    //上传所有图片
    private void uploadAllPhoto() {
        if (("").equals(installerET.getText().toString())) {
            ToastUtil.show("姓名不能为空");
            return;
        }
        boolean phoneIsOk = PhoneUtil.checkCellphone(installerPhoneET.getText().toString());
        if (("").equals(installerPhoneET.getText().toString())
                || !phoneIsOk) {
            ToastUtil.show("请输入11位有效电话号码");
            return;
        }
        if (!ValidUtil.validPhone(installerPhoneET.getText().toString())) {
            ToastUtil.show("请输入11位有效电话号码");
            return;
        }

        if (eqnoLoginBean.getResult() != null && "3".equals(eqnoLoginBean.getResult().getStatus())) {
            ToastUtil.show("该设备未启用");
            return;
        }

        if (installPosition.length() == 0) {
            ToastUtil.show("手机可能未定位，正在重新定位您的位置");
            initLocation();
            return;
        }

        if (tracingResult == null || tracingResult.getPostType() == null || tracingResult.getPositionTime() == null || tracingResult.getGdLat() == 0) {
            ToastUtil.show("该设备未定位");
            return;
        }

        if (tracingResult.getPostType().equals("LBS")) {
            ToastUtil.show("GPS信号弱，请重新定位");
            return;
        }

        double distance = Utils.calculateLineDistance(mCurAMapLocation.getLatitude(), mCurAMapLocation.getLongitude(), tracingResult.getGdLat(), tracingResult.getGdLng());
        Log.e("hyhyhyhyhyhy距离是：",distance+"");
        if (distance > 500.0) {
            ToastUtil.show("请在安装现场拍照");
            return;
        }

        /** 比较定位时间*/
        /**
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * !
         * */
        int disTime = Utils.compareTime(tracingResult.getPositionTime(), Utils.getNowTime());
        //Log.e("hyhyhyhyhyhy",disTime+"");
        if (disTime > 30) {
            ToastUtil.show("定位失效，请重新定位");
            return;
        }

        for (LocalMedia media : picsList) {
            if (media.getPath() == null) {
                ToastUtil.show("照片不完整");
                return;
            }
        }

        /** 开始上传图片*/

        DialogUtil.show(mContext);

        new Thread(){
            @Override
            public void run() {
                for (int index = 0; index < picsList.size(); index++) {
                    int finalIndex = index;
                    mContext.runOnUiThread(() -> DialogUtil.setContent("正在压缩第" + (finalIndex + 1) + "张图片"));
                    compressImage(picsList.get(index).getPath(), index);
                    //Log.e("88888777", "压缩第" + (index + 1) + "张");
                }
                uploadNormalFiles();
            }
        }.start();
    }

    public String getPhoneModel() {
        return android.os.Build.MODEL;
    }

    private void uploadNormalFiles() {

        Map<String, String> params = new HashMap<>();
        params.put("eqId", eqnoLoginBean.getResult().getEqId());
        params.put("eqPosition", eqPosition);
        params.put("installer", installerET.getText().toString());
        params.put("installerPhone", installerPhoneET.getText().toString());
        params.put("installerPosition", installPosition + "--来自"+getPhoneModel());

        MultipartBody multipartBody = fetchNormalMutipartBody(params);

        ProgressRequestBody requestBody = new ProgressRequestBody(multipartBody, new ProgressRequestBody.UploadCallbacks() {

            @Override
            public void onProgress(long totalLen, long writtenLen) {
                mContext.runOnUiThread(() -> DialogUtil.setContent("正在上传图片：" + 100 * writtenLen / totalLen + "%"));
                Log.e("666666", "progress = " + 100 * writtenLen / totalLen + "%");
            }
        });

        Api.getInstance().createService()
                .uploadFiles(requestBody)
                .compose(RxSchedulers.observableIO2Main(mContext))
                .subscribe(new ProgressObserver<UploadImageBean>(mContext, false) {

                    @Override
                    public void onSuccess(UploadImageBean result) {
                        new Handler().postDelayed(() -> {
                            DialogUtil.dismiss();
                            ToastUtil.show("上传成功");
                            finish();
//                            Intent intent = new Intent(PhotoActivity.this, OpenFragmentActivity.class);
//                            startActivity(intent);
                        }, 2 * 1000);
                    }

                    @Override
                    public void onFailure(ErrorException e) {
                        DialogUtil.dismiss();
                        ToastUtil.show("图片上传失败["+e.getMsg()+"]");
                    }
                });
    }

    public MultipartBody fetchSupplementMutipartBody(int index) {

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        builder.addFormDataPart("eqId", eqnoLoginBean.getResult().getEqId());
        builder.addFormDataPart("type", typeList.get(index));

        List<LocalMedia> picsList_ = new ArrayList<>();
        for (LocalMedia m : picsList) {
            if (m.getCompressPath() != null) {
                picsList_.add(m);
            }
        }

        File file = new File(picsList_.get(index).getCompressPath());

        builder.addFormDataPart("img", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file));

        return builder.build();
    }

    public MultipartBody fetchNormalMutipartBody(final Map<String, String> params) {

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        for (String key : params.keySet()) {
            builder.addFormDataPart(key, params.get(key));
        }

        for (LocalMedia media : picsList) {
            if (media.getCompressPath() != null) {
                File file = new File(media.getCompressPath());
                builder.addFormDataPart("img", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file));
            }
        }

        return builder.build();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    picsList.set(0, PictureSelector.obtainMultipleResult(data).get(0));
                    showImage();
                    break;
                case 2:
                    picsList.set(1, PictureSelector.obtainMultipleResult(data).get(0));
                    showImage();
                    break;
                case 3:
                    picsList.set(2, PictureSelector.obtainMultipleResult(data).get(0));
                    showImage();
                    break;
            }
        }
    }

    /** 同步图片压缩*/
    private String compressImage(String filePath, int index) {

        String path = mContext.getApplicationContext().getExternalCacheDir().getAbsolutePath() + "/upload";

        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        Log.e("76666",filePath);

        Bitmap bitmap = BitmapFactory.decodeFile(filePath);

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
            String fileName = sdf.format(System.currentTimeMillis());
            String outpath = path + "/" + fileName + "_" + index + ".JPEG";

            BitmapUtils.compressAndGenImage(bitmap, outpath, 500);
            Log.e("766668888877777",outpath);

            picsList.get(index).setCompressPath(outpath);

            return outpath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void showImage() {

        RequestOptions options = new RequestOptions()
                .override(1000,1000);

        if (picsList.get(0).getPath() != null) {
            Glide.with(this).load(picsList.get(0).getPath()).apply(options).into(imageView1);
        }

        if (picsList.get(1).getPath() != null) {
            Glide.with(this).load(picsList.get(1).getPath()).apply(options).into(imageView2);
        }

        if (picsList.get(2).getPath() != null) {
            Glide.with(this).load(picsList.get(2).getPath()).apply(options).into(imageView3);
        }
    }

    public void initLocation() {
        mlocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 获取一次定位结果
        mLocationOption.setOnceLocation(false);
        // 获取最近3s内精度最高的一次定位结果
        mLocationOption.setOnceLocationLatest(false);
        mLocationOption.setInterval(10 * 1000);
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        mlocationClient.startLocation();

        loadRealTracing();
        loadEqStatus();
    }

    AMapLocation mCurAMapLocation = null;


    public void initGeocodeSearch(){

        installerGeocodeSearch = new GeocodeSearch(this);
        installerGeocodeSearch.setOnGeocodeSearchListener(this);

        eqGeocodeSearch = new GeocodeSearch(this);
        eqGeocodeSearch.setOnGeocodeSearchListener(this);
    }

    @SuppressLint({"SetTextI18n", "DefaultLocale"})
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result.getRegeocodeQuery() == installerRegeocodeQuery) {
                /** 手机定位*/
                if (result != null && result.getRegeocodeAddress() != null
                        && result.getRegeocodeAddress().getFormatAddress() != null) {
                    RegeocodeAddress info = result.getRegeocodeAddress();

                    String eqPo;

                    if (info.getPois().size() == 0) {
                        eqPo = info.getFormatAddress();
                    } else {
                        PoiItem poi = info.getPois().get(0);
                        String poiName = poi.getTitle();

                        if (info.getFormatAddress().contains(poiName)) {
                            poiName = "";
                        }

                        eqPo = info.getFormatAddress() +
                                poiName + " " +
                                getDir(poi.getDirection()) + " " +
                                poi.getDistance() + "米";
                    }

                    installPosition = eqPo + "(" +
                            Double.parseDouble(String.format("%.6f",result.getRegeocodeQuery().getPoint().getLatitude())) + "," +
                            Double.parseDouble(String.format("%.6f",result.getRegeocodeQuery().getPoint().getLongitude())) + ")";
                    Log.e("ppp手机",installPosition);

                }
            } else if (result.getRegeocodeQuery() == eqRegeocodeQuery) {
                /** 设备定位*/

                if (result != null && result.getRegeocodeAddress() != null
                        && result.getRegeocodeAddress().getFormatAddress() != null) {
                    RegeocodeAddress info = result.getRegeocodeAddress();

                    //Log.e("sssss999",info.getFormatAddress()+"-"+info.getBuilding()+"-"+info.getDistrict()+"-"+info.getTownship()+"-"+info.getDistrict()+"-"+info.getNeighborhood()+info.getBusinessAreas());

                    String eqPo;

                    if (info.getPois().size() == 0) {
                        eqPo = info.getFormatAddress();
                    } else {
                        PoiItem poi = info.getPois().get(0);
                        String poiName = poi.getTitle();
                        if (info.getFormatAddress().contains(poiName)) {
                            poiName = "";
                        }
                        eqPo = info.getFormatAddress() +
                                poiName + " " +
                                getDir(poi.getDirection()) + " " +
                                poi.getDistance() + "米";
                    }

                    eqPosition = eqPo + "(" +
                            tracingResult.getGdLat() + "," +
                            tracingResult.getGdLng() + ")";

                    eqPositionTV.setText("定位位置："+eqPo+"(" +
                            tracingResult.getPostType() + "定位" + ")" + "(" +
                            tracingResult.getGdLat() + "," +
                            tracingResult.getGdLng() + ")");
                    Log.e("pppp设备", eqPosition);
                }
            }
        } else {
            //addressName = "当前地址获取失败";
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {}

    /** 手机定位信息*/
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                mCurAMapLocation = aMapLocation;
                /** onLocationChanged返回信息不全，所以得通过GeocodeSearch获取详细逆地理信息*/
                LatLonPoint latLonPoint = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                installerRegeocodeQuery = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP);
                installerGeocodeSearch.getFromLocationAsyn(installerRegeocodeQuery);
            } else {
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
        /** 10秒刷新一次位置*/
        loadRealTracing();
        loadEqStatus();
    }

    public String getDir(String dir){

        String direction = "";

        if (dir.equals("北")) {
            direction = "南";
        } else if (dir.equals("东北")) {
            direction = "西南";
        } else if (dir.equals("东")) {
            direction = "西";
        } else if (dir.equals("东南")) {
            direction = "西北";
        } else if (dir.equals("南")) {
            direction = "北";
        } else if (dir.equals("西南")) {
            direction = "东北";
        } else if (dir.equals("西")) {
            direction = "东";
        } else if (dir.equals("西北")) {
            direction = "东南";
        }

        return direction;
    }

    private void loadRealTracing() {
        Api.getInstance().createService()
                .loadTracing(eqnoLoginBean.getResult().getEqNo())
                .compose(RxSchedulers.observableIO2Main(this))
                .subscribe(new ProgressObserver<TracingBean>(this, false) {
                    @Override
                    public void onSuccess(TracingBean result) {
                        /** 发起逆地理请求*/
                        LatLonPoint latLonPoint = new LatLonPoint(result.getResult().get(0).getGdLat(), result.getResult().get(0).getGdLng());
                        eqRegeocodeQuery = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP);
                        eqGeocodeSearch.getFromLocationAsyn(eqRegeocodeQuery);
                        // 定位Model
                        tracingResult = result.getResult().get(0);

                        timeTV.setText("定位时间：" + tracingResult.getPositionTime());
                    }

                    @Override
                    public void onFailure(ErrorException e) {

                    }
                });
    }

    /** 查询设备状态*/
    public void loadEqStatus() {
        Api.getInstance().createService().eqnoLogin(eqnoLoginBean.getResult().getEqNo())
                .compose(RxSchedulers.observableIO2Main(mContext))
                .subscribe(new ProgressObserver<EqnoLoginBean>(mContext,false) {
                    @Override
                    public void onSuccess(EqnoLoginBean result) {
                        eqnoLoginBean = result;
                        // 设备状态
                        statusTV.setText("设备状态：" + getStatus(eqnoLoginBean.getResult().getStatus()));
                    }

                    @Override
                    public void onFailure(ErrorException e) { }

                });
    }

    public String getStatus(String status) {
        if (status.equals("3")) {
            return "未启用";
        } else if (status.equals("2")) {
            return "离线";
        } else {
            return "在线";
        }
    }

    public String getStatus(){
        if (eqnoLoginBean != null) {
            String status = eqnoLoginBean.getResult().getStatus();
            if (status.equals("3")) {
                return "未启用";
            } else if (status.equals("2")) {
                return "离线";
            } else {
                return "在线";
            }
        }
        return "正在获取...";
    }

    /** 检查照片数量*/
    private void uploadFiles() {
        /** 完整上传提交*/
        if (uploadImgType == UploadImgType.UploadImgTypeNormal) {
            uploadAllPhoto();
        } else {
            /** 补拍提交*/
            uploadSupplementPhoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_PERMISSION) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
            } else {
                ToastUtil.show("请给予权限");
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.CAMERA}
                , REQUEST_PERMISSION);
    }
}